const app = getApp()
const request = require('../../../utils/request.js');

Page({
  data: {
    id: '', // 编辑模式下的ID
    isEdit: false, // 是否为编辑模式
    name: '',
    categoryIndex: 0,
    categories: ['秸秆', '稻壳', '玉米芯', '花生壳', '其他'],
    price: '',
    unitIndex: 0,
    units: ['吨', '公斤', '立方米', '包'],
    quantity: '',
    productionDate: '',
    shelfLife: '',
    storageCondition: '',
    transportMethodIndex: 0,
    transportMethods: ['公路运输', '铁路运输', '水路运输', '航空运输'],
    origin: [],
    originCode: [],
    description: '',
    images: [],
    imageUrls: []
  },

  onLoad(options) {
    if (options.id) {
      // 编辑模式
      this.setData({
        id: options.id,
        isEdit: true
      });
      this.loadSupplyDetail(options.id);
    }
  },

  // 加载供应详情
  loadSupplyDetail(id) {
    // 模拟加载数据
    request.request({
      url: `${app.globalData.baseUrl}/api/residues/${id}`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${app.getGlobalToken()}`
      },
      success: (res) => {
        const data = res.data.data
        data.origin = data.origin.split('/')
        data.originCode = JSON.parse(data.originCode)
        this.setData({
          ...data,
          images: data.images.map((item) => app.globalData.baseUrl + item),
          imageUrls:data.images
        })
      },
      fail: (err) => {
        wx.showToast({
          title: '加载失败',
          icon: 'none'
        })
        console.error('加载商品详情失败:', err)
      },
      complete: () => {
        //
      }
    })
  },

  // 标题输入
  onTitleInput(e) {
    this.setData({
      name: e.detail.value
    })
  },

  // 分类选择
  onCategoryChange(e) {
    this.setData({
      categoryIndex: e.detail.value
    })
  },

  // 价格输入
  onPriceInput(e) {
    this.setData({
      price: e.detail.value
    })
  },

  // 单位选择
  onUnitChange(e) {
    this.setData({
      unitIndex: e.detail.value
    })
  },

  // 数量输入
  onQuantityInput(e) {
    this.setData({
      quantity: e.detail.value
    })
  },

  // 生产日期选择
  onProductionDateChange(e) {
    this.setData({
      productionDate: e.detail.value
    })
  },

  // 保质期输入
  onShelfLifeInput(e) {
    this.setData({
      shelfLife: e.detail.value
    })
  },

  // 保质期单位选择
  onShelfLifeUnitChange(e) {
    this.setData({
      shelfLifeUnitIndex: e.detail.value
    })
  },

  // 储存条件选择
  onStorageConditionInput(e) {
    this.setData({
      storageCondition: e.detail.value
    })
  },

  // 运输方式选择
  onTransportMethodChange(e) {
    this.setData({
      transportMethodIndex: e.detail.value
    })
  },

  // 地区选择
  onRegionChange(e) {
    this.setData({
      origin: e.detail.value,
      originCode: e.detail.code
    })
  },

  // 描述输入
  onDescriptionInput(e) {
    this.setData({
      description: e.detail.value
    })
  },

  // 选择图片
  chooseImage() {
    let me = this;
    wx.chooseImage({
      count: 9 - this.data.images.length,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePaths = res.tempFilePaths
        wx.uploadFile({
          url: `${app.globalData.baseUrl}/api/files/upload`,
          filePath: tempFilePaths[0],
          name: 'file',
          header: {
            'Authorization': `Bearer ${app.getGlobalToken()}`
          },
          success(res) {
            const {
              data
            } = JSON.parse(res.data)
            me.setData({
              images: [...me.data.images, ...tempFilePaths],
              imageUrls: [...me.data.imageUrls, data]
            })
          },
          fail: () => {
            wx.showToast({
              title: '上传图片失败',
              icon: 'none'
            })
          }
        })
      }
    })
  },

  // 删除图片
  deleteImage(e) {
    const index = e.currentTarget.dataset.index
    const images = this.data.images
    const imageUrls = this.data.imageUrls
    images.splice(index, 1)
    imageUrls.splice(index, 1)
    this.setData({
      images,
      imageUrls
    })
  },

  // 表单验证
  validateForm() {
    if (!this.data.name) {
      wx.showToast({
        title: '请输入标题',
        icon: 'none'
      })
      return false
    }

    if (!this.data.price) {
      wx.showToast({
        title: '请输入价格',
        icon: 'none'
      })
      return false
    }

    if (!this.data.quantity) {
      wx.showToast({
        title: '请输入数量',
        icon: 'none'
      })
      return false
    }

    if (!this.data.productionDate) {
      wx.showToast({
        title: '请选择生产日期',
        icon: 'none'
      })
      return false
    }

    if (!this.data.shelfLife) {
      wx.showToast({
        title: '请输入保质期',
        icon: 'none'
      })
      return false
    }

    if (!this.data.origin.length) {
      wx.showToast({
        title: '请选择产地',
        icon: 'none'
      })
      return false
    }

    if (!this.data.description) {
      wx.showToast({
        title: '请输入描述',
        icon: 'none'
      })
      return false
    }
    return true
  },

  // 提交表单
  submitForm() {
    if (!this.validateForm()) return

    // 显示加载中
    wx.showLoading({
      title: '发布中...'
    })

    // 提交表单数据
    request.request({
      url: `${app.globalData.baseUrl}/api/residues`,
      method: 'POST',
      data: {
        id: this.data.id,
        name: this.data.name,
        type: this.data.categories[this.data.categoryIndex],
        description: this.data.description,
        image: this.data.imageUrls[0],
        images: this.data.imageUrls,
        origin: this.data.origin.join('/'),
        originCode: JSON.stringify(this.data.originCode),
        productionDate: this.data.productionDate,
        shelfLife: this.data.shelfLife,
        storageCondition: this.data.storageCondition,
        transportMethod: this.data.transportMethods[this.data.transportMethodIndex],
        price: this.data.price,
        quantity: this.data.quantity,
        unit: this.data.units[this.data.unitIndex]
      },
      header: {
        'Authorization': `Bearer ${app.getGlobalToken()}`
      },
      success: (res) => {
        wx.showToast({
          title: '发布成功',
          icon: 'success'
        })
        app.globalData.needRefresh = true;
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/supply/supply',
          })
        }, 1500)
      },
      fail: () => {
        wx.showToast({
          title: '发布失败',
          icon: 'none'
        })
        console.error('发布失败:', err)
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  }
})